import esriLoader from 'esri-loader'
var addWhere = function (objs, relation) {
  var where = "",
    isFirst = true;
  for (var i = 0; i < objs.length; i++) {
    var name = objs[i].name,
      value = objs[i].value,
      symbol = objs[i].symbol,
      fieldTemplate = "",
      fieldWhere = "";
    if (symbol == "=") {
      if (typeof value == "string") {
        fieldTemplate = "" + name + symbol + "'" + value + "'";
      } else if (typeof value == "number") {
        fieldTemplate = "" + name + symbol + value;
      }
    } else if (symbol == "<>") {
      symbol = "!="
      if (typeof value == "string") {
        fieldTemplate = "" + name + symbol + "'" + value + "'";
      } else if (typeof value == "number") {
        fieldTemplate = "" + name + symbol + value;
      } else if (symbol == ">=" || symbol == "<=" || symbol == "<") {
        if (typeof value == "number") {
          fieldTemplate = "" + name + symbol + value;
        } else {
          fieldTemplate = "";
          console.log("数据不符合要求");
        }
      } else if (symbol == "包含") {
        if (typeof value == "string") {
          symbol = "like"
          fieldTemplate = "" + name + symbol + "'%" + value + "%'";
        } else if (lang.isArray(value)) {
          symbol = "in"
          fieldTemplate = "" + name + symbol + "'(" + value + ")'";
        }
      } else if (symbol == "不包含") {
        if (typeof value == "string") {
          symbol = "not like"
          fieldTemplate = "" + name + symbol + "'%" + value + "%'";
        } else if (lang.isArray(value)) {
          symbol = "not in"
          fieldTemplate = "" + name + symbol + "'" + value + "'";
        }
      } else if (symbol == "为空") {
        symbol = "is"; value = "null"
        fieldTemplate = "" + name + symbol + value;
      } else if (symbol == "不为空") {
        symbol = "not"; value = "null"
        fieldTemplate = "" + name + symbol + value;
      }
    }
    if (isFirst) {
      where = fieldTemplate;
      isFirst = false;
    } else {
      where += relation + fieldTemplate;
    }
  }
  where = where ? where : "1=1";
  return where;

}
var query = function (layer, geometry, spatialRelationship, mapId, querWhere) {
  var self = this;
  esriLoader.loadModules(["widget/MapManager", "widget/GraphicsLayerManager", "widget/task/QueryTask", "widget/graphicUtils", "esri/layers/ImageParameters", "esri/layers/ArcGISDynamicMapServiceLayer", "esri/layers/MapImageLayer", "esri/layers/MapImage"])
    .then(([MapManager, GraphicsLayerManager, QueryTask, graphicUtils, ImageParameters, ArcGISDynamicMapServiceLayer, MapImageLayer, MapImage]) => {
      var map = MapManager.getMap(mapId);
      var queryLayer = map.getLayer(layer.label);
      var imageParameters = new ImageParameters();
      if (geometry && geometry.type != "point") {
        imageParameters.bbox = geometry.getExtent();
      }
      if (querWhere) {
        var where = addWhere(querWhere.queryFiled, querWhere.relation);
        var layerDefs = [];
        layerDefs[layer.ILayer.QueryIndexArray] = where;
        imageParameters.layerDefinitions = layerDefs;
      }
      queryLayer.setVisibility(false);
      var mil = map.getLayer("exportMapImage");;
      if (!mil) {
        mil = new MapImageLayer({
          'id': "exportMapImage"
        });
        map.addLayer(mil);
      } else {
        mil.removeAllImages()
      }
      queryLayer.exportMapImage(imageParameters, function (evt) {
        var mapImage = new MapImage({
          'extent': evt.extent,
          'href': evt.href
        });
        mil.addImage(mapImage);
      });
    })
    .catch(err => {
      // handle any script or module loading errors
      console.error(err);
    })
}
/*
* 当清除数据后 还原数据
*/
var clearQuery = function (layer, mapId) {
  var self = this;
  esriLoader.loadModules(["widget/MapManager"])
    .then(([MapManager]) => {
      var map = MapManager.getMap(mapId);
      var queryLayer = map.getLayer(layer.label);
      queryLayer.setVisibility(true);
      var mil = map.getLayer("exportMapImage");
      if (mil) {
        map.removeLayer(mil)
      }
    })
    .catch(err => {
      // handle any script or module loading errors
      console.error(err);
    })
}
var queryByNormal=function(layer, mapId, querWhere){
  var self = this;
  esriLoader.loadModules(["widget/MapManager", "widget/GraphicsLayerManager", "widget/task/QueryTask", "widget/graphicUtils", "esri/layers/ImageParameters", "esri/layers/ArcGISDynamicMapServiceLayer", "esri/layers/MapImageLayer", "esri/layers/MapImage"])
    .then(([MapManager, GraphicsLayerManager, QueryTask, graphicUtils, ImageParameters, ArcGISDynamicMapServiceLayer, MapImageLayer, MapImage]) => {
      var map = MapManager.getMap(mapId);
      map.infoWindow.hide();
      var queryLayer = map.getLayer(layer.label);
      var imageParameters = new ImageParameters();
      var currentLayerServiceUrl=layer.ILayer.QueryUrl;
      if (querWhere) {
        //var where = addWhere(querWhere.queryFiled, querWhere.relation);
        var layerDefs = [];
        layerDefs[layer.ILayer.QueryIndexArray] = querWhere;
        imageParameters.layerDefinitions = layerDefs;
      }
      queryLayer.setVisibility(false);
      var mil = map.getLayer("exportMapImage");;
      if (!mil) {
      
        mil = new ArcGISDynamicMapServiceLayer(currentLayerServiceUrl, { "imageParameters": imageParameters, "id": "exportMapImage", "opacity": 0.6 });
        map.addLayer(mil);
      } else {
       // mil.removeAllImages()
      }
  
    })
    .catch(err => {
      // handle any script or module loading errors
      console.error(err);
    })
}
var queryByNormal2=function(layer, mapId, querWhere){
  var self = this;
  esriLoader.loadModules(["widget/MapManager", "widget/GraphicsLayerManager", "widget/task/QueryTask", "widget/graphicUtils", "esri/layers/ImageParameters", "esri/layers/ArcGISDynamicMapServiceLayer", "esri/layers/MapImageLayer", "esri/layers/MapImage"])
    .then(([MapManager, GraphicsLayerManager, QueryTask, graphicUtils, ImageParameters, ArcGISDynamicMapServiceLayer, MapImageLayer, MapImage]) => {
      var map = MapManager.getMap(mapId);
      map.infoWindow.hide();
      var queryLayer = map.getLayer(layer.label);
      var imageParameters = new ImageParameters();
      if (querWhere) {
        //var where = addWhere(querWhere.queryFiled, querWhere.relation);
        var layerDefs = [];
        layerDefs[layer.ILayer.QueryIndexArray] = querWhere;
        imageParameters.layerDefinitions = layerDefs;
      }
      queryLayer.setVisibility(false);
      var mil = map.getLayer("exportMapImage");;
      if (!mil) {
        mil = new MapImageLayer({
          'id': "exportMapImage"
        });
        map.addLayer(mil);
      } else {
        mil.removeAllImages()
      }
      queryLayer.exportMapImage(imageParameters, function (evt) {
        var mapImage = new MapImage({
          'extent': evt.extent,
          'href': evt.href
        });
        mil.addImage(mapImage);
      });
    })
    .catch(err => {
      // handle any script or module loading errors
      console.error(err);
    })
}
var queryByClick = function (data, layerArray) {
  esriLoader.loadModules(["esri/tasks/IdentifyTask", "esri/tasks/IdentifyParameters"])
    .then(([IdentifyTask, IdentifyParameters]) => {
var  attributes="";
      //for (var i = 0; i < layerArray.length; i++) {
        if(layerArray.length){
        var i=layerArray.length-1;
        if (layerArray[i].IsQuery) {
          var identifyTask = new IdentifyTask(layerArray[i].ILayer.QueryUrl);

          var identifyParameters = new IdentifyParameters();

          identifyParameters.tolerance = 6;

          identifyParameters.returnGeometry = true;

          identifyParameters.layerOption = IdentifyParameters.LAYER_OPTION_ALL;

          identifyParameters.layerIds = [parseFloat(layerArray[i].ILayer.QueryIndexArray)];

          identifyParameters.geometry = data.point;

          //screenP = map.toScreen(mapPoint);
          attributes=layerArray[i].IFileds;
          identifyParameters.mapExtent = data.map.extent;
          identifyParameters.width = data.map.width;
          identifyParameters.height = data.map.height;

          identifyTask.execute(identifyParameters, function (result) {
            IdentifyResultManager(result, data,attributes);
          });
        }
      }
    })

}
function IdentifyResultManager(IdentifyResult, data, fields) {
  if (IdentifyResult.length > 0) {
    for (var i = 0; i < IdentifyResult.length; i++) {
      var layerName = IdentifyResult[i].layerName;
      var myFeature = IdentifyResult[i].feature;
    }
    var keys = IdentifyResult[0].feature.attributes;
    var geo = IdentifyResult[0].feature.geometry;
   // var p=new esriLoader.point();
   /*  if(geo.type=="polygon"||geo.type=="polyline"){
      p=geo.getExtent().getCenter();
    } */
    //var 
    //setSymbol(geo, keys);
    var content = getContent(keys, fields);
    data.map.infoWindow.setTitle("详细信息");
    data.map.infoWindow.setContent(content);
    data.map.infoWindow.show(data.point);
  }
}
function getContent(keys, fields) {
  var content = "";
  content += "<table class='keyValue'>";
  if (fields.length) {
    for (var i = 0; i < fields.length; i++) {

      if (!fields[i].IsDisplay)
        continue;
      var s_key = fields[i].Name.toLowerCase();
      var b_key = fields[i].Name.toUpperCase();


      var value = keys[fields[i].Name]||keys[fields[i].Alias];
      if (!value || value == "null" || value == null|| value == "Null") {
        value = "";
      }
      content += "<tr>"
      content += "<td>" + fields[i].Alias + "</td>" + "<td>" + value + "</td>"
      content += "<tr>"
      /* if(fields[i].Name==key){
        attr=fields[i].Alias;
        break;
      }else if(fields[i].Alias==key){
        attr=fields[i].Alias;
        break;
      } */
    }
  } else {

    for (var key in keys) {
      var s_key = key.toLowerCase();
      var attr = "";

      if (s_key.indexOf("shape") > -1 || s_key.indexOf("object") > -1) {
        continue;
      }
      for (var i = 0; i < fields.length; i++) {
        if (fields[i].Name == key) {
          attr = fields[i].Alias;
          break;
        } else if (fields[i].Alias == key) {
          attr = fields[i].Alias;
          break;
        }
      }
      // else if (MapConfig.layerAttr[key]) {

      var value = keys[key];
      if (!value || value == "null" || value == null|| value == "Null") {
        value = "";
      }
      content += "<tr>"
      content += "<td>" + key + "</td>" + "<td>" + value + "</td>"
      content += "<tr>"

      // }
    }
  }
  content += "</table>";
  return content;
}

export default {
  query, queryByClick,clearQuery,queryByNormal
}
